package com.edgardeng.publish_subscribe.route;

import com.edgardeng.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;

/**
 * RabbitMQ 测试 Publish/Subscribe  - 消费者接收消息
 *
 */
public class ReceiverTwo {

    private static String queue = "test_queue_direct_two";
    public static void main(String[] args) throws Exception {

        String exchange = ConnectionUtil.EXCHANGE_NAME_DIRECT;

        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(queue, false, false, false, null);

        String bindKey1 = ConnectionUtil.ROUTER_KEY_DIRECT_ONE;
        String bindKey3 = ConnectionUtil.ROUTER_KEY_DIRECT_THREE;

        // 绑定队列到交换机
        channel.queueBind(queue, exchange, bindKey1); // arg3：bind Key
        channel.queueBind(queue, exchange, bindKey3); // arg3：bind Key

        System.out.println(" [*] Waiting for messages. queue:" + queue + "   exchange:" + exchange + "   bindKEY:" + bindKey1 + "/" + bindKey3);

        // 声明一个回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("[Receiver at queue: " + queue + "] " + message );
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //
        };
        // 接收消息 arg1：队列名 arg2 是否自动确认，arg3 接收回调 arg4 取消回调
        channel.basicConsume(queue, false, deliverCallback, consumerTag -> { });

    }
}
